"""
Case Type   : 内核告警
Case Name   : 该功能涉及CM相关环境，CI和门禁环境均无CM环境，前置条件先安装CM
Create At   : 2025-10-10
Owner       : lvlintao
Description :
    1、检查CM环境
    2、清理环境
Expect      :
    1、CM环境正常
    2、清理环境
History     :
"""
import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.ComInstall import CmInstall
from testcase.utils.ComInstall import CmUnInstall
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

logger = Logger()

class AlarmReportTestCase(unittest.TestCase):
    def setUp(self):
        text = f'-----{os.path.basename(__file__)} start-----'
        logger.info(text)
        self.constant = Constant()
        self.common = Common('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.root_nodes = (Node('PrimaryRoot'), Node('Standby1Root'),
                           Node('Standby2Root'))
        self.user_nodes = (Node('PrimaryDbUser'), Node('Standby1DbUser'),
                           Node('Standby2DbUser'))
        self.install_pkg_path = os.path.dirname(macro.DB_SCRIPT_PATH)
        self.cm = CmInstall(self.install_pkg_path, self.pri_sh.node.ssh_user)
        status = self.pri_sh.get_db_cluster_status()
        if "Degraded" in status or "Normal" in status:
            res = self.pri_sh.restart_db_cluster(get_detail=True)
            logger.info(res)
            self.assertIn('Successfully started', res, '执行失败:' + text)

    def test_alarm_report(self):
        text = '--step 1:检查cm环境;expect:成功'
        logger.info(text)
        show_status = f'source {macro.DB_ENV_PATH};' \
                      f'cm_ctl query -Civdp'
        status_msg = self.common.get_sh_result(self.user_nodes[0], show_status)
        self.assertIn("CMServer State", status_msg, "执行失败:" + text)

    def tearDown(self):
        text = '--step 2:清理环境;expect:成功--'
        logger.info(text)
        self.un_cm = CmUnInstall(self.install_pkg_path,
                                 self.pri_sh.node.ssh_user)
        res = self.un_cm.cm_uninstall(
            self.user_nodes[0], '--deleteData --deleteBinary')
        self.assertIn('Uninstall CM tool success', res, f'执行失败: {text}')
        logger.info(f'-----{os.path.basename(__file__)} end-----')